<?php
declare (strict_types = 1);

namespace app\admin\model\system;

use bbweb\traits\ModelTrait;
use bbweb\basic\BaseModel;
use think\facade\Session;
use think\facade\Config;

/**
 * @mixin \think\Model
 */
class SystemAdmin extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'system_admin';

    use ModelTrait;

    protected $insert = ['add_time'];

    // 设置字段信息
    protected $schema = [
        'id'			=> 'int',
        'account'		=> 'varchar',
        'password'		=> 'char',
        'real_name'		=> 'varchar',
        'phone'		    => 'varchar',
        'roleid'		=> 'int',
        'last_ip'		=> 'varchar',
        'last_time'		=> 'int',
        'add_time'		=> 'int',
        'login_count'	=> 'int',
        'level'			=> 'tinyint',
        'status'		=> 'tinyint',
        'is_del'		=> 'tinyint',
        'update_at'     => 'int'
    ];

    public static function setAddTimeAttr()
    {
        return time();
    }

    /**
     * 用户登陆
     * @param $account
     * @param $pwd
     * @return bool
     */
    public static function login($account, $password)
    {
        $staff = Config::get('hello.admin');
        if($account == $staff['username'] && $password == $staff['password']) {
            Session::set('adminId', $staff['id']);
            Session::set('adminInfo', $staff);
            Session::set('login_at', time());
            Session::save();
        } else {
            $adminInfo = self::get(compact('account'));
            if (!$adminInfo || $adminInfo['is_del']) return self::setErrorInfo('登陆的账号不存在!');
            if ( $adminInfo['password'] != md5(md5($password).Config::get('hello.secret')) ) return self::setErrorInfo('账号或密码错误，请重新输入');
            if (!$adminInfo['status']) return self::setErrorInfo('该账号已被关闭!');
            self::setLoginInfo($adminInfo);
            event('SystemAdminLoginAfter', [$adminInfo]);
        }
        return true;
    }

    /**
     *  保存当前登陆用户信息
     */
    public static function setLoginInfo($adminInfo)
    {
        Session::set('adminId', $adminInfo['id']);
        Session::set('adminInfo', $adminInfo->toArray());
        Session::set('login_at', time());
        Session::save();
    }

    /**
     * 清空当前登陆用户信息
     */
    public static function clearLoginInfo()
    {
        Session::delete('adminInfo');
        Session::delete('adminId');
        Session::delete('login_at');
        Session::save();
    }

    /**
     * 检查用户登陆状态
     * @return bool
     */
    public static function hasActiveAdmin()
    {
        $expire = Config::get('hello.admin.expire') ?: 3600;
        if ( !Session::has('adminId') || !Session::has('adminInfo') || !Session::has('login_at') || time() - Session::get('login_at') > $expire) {
            self::clearLoginInfo();
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获得登陆用户信息
     * @return mixed
     * @throws \Exception
     */
    public static function activeAdminInfoOrFail()
    {
        $adminInfo = Session::get('adminInfo');
        if (!$adminInfo) return self::setErrorInfo('请登陆');
        if (!$adminInfo['status']) return self::setErrorInfo('该账号已被关闭!');
        return $adminInfo;
    }

    /**
     * @return array|null
     * @throws \Exception
     */
    public static function activeAdminAuthOrFail()
    {
        $adminInfo = self::activeAdminInfoOrFail();
        if(!$adminInfo) return [];
        if (is_object($adminInfo)) $adminInfo = $adminInfo->toArray();
        return $adminInfo['level'] === 0 ? SystemRole::getAllAuth() : SystemRole::rolesByAuth($adminInfo['roleid']);
    }

    /**
     * 获得有效管理员信息
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public static function getValidAdminInfoOrFail($id)
    {
        $adminInfo = self::get($id);
        if (!$adminInfo) return self::setErrorInfo('用户不存在!');
        if (!$adminInfo['status']) return self::setErrorInfo('该账号已被关闭!');
        return $adminInfo;
    }
}
